﻿using Autofac;
using Autofac.Integration.Mvc;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using WeChat.Web.Filter;

namespace WeChat.Web
{
    public class AutoFacBootStrapper
    {
        public static void AutoFacInit()
        {
            var builder = new ContainerBuilder();

            // Register your MVC controllers.开启属性注入
            builder.RegisterControllers(typeof(AutoFacBootStrapper).Assembly).PropertiesAutowired();

            // OPTIONAL: Enable property injection into action filters.
            builder.RegisterFilterProvider();

            SetupResolveRules(builder);

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        private static void SetupResolveRules(ContainerBuilder builder)
        {
            //加载数据仓储层
            var assemblyDao = Assembly.Load("WeChat.Dao");

            //业务管理层
            var assemblyManager = Assembly.Load("WeChat.Manager");

            builder.RegisterAssemblyTypes(assemblyDao).Where(
                type =>
                    type.Name.EndsWith("Repository") && //以Repository结尾的仓储类
                    type.Namespace.Equals("WeChat.Dao.Implement") //限定仓储实例命名空间
                    ).AsImplementedInterfaces().PropertiesAutowired().SingleInstance(); //实例化全部匹配仓储类

            builder.RegisterAssemblyTypes(assemblyManager).Where(
                type =>
                    type.Name.EndsWith("Manager") && //以Manager结尾的业务类
                    type.Namespace.Equals("WeChat.Manager.Implement")) //限定业务实例命名空间
                .AsImplementedInterfaces().PropertiesAutowired().SingleInstance(); //实例化全部匹配业务类

            //builder.RegisterType<待注入的类类型>().AsSelf().PropertiesAutowired();

            //注册异常拦截器
            builder.RegisterType<LogHandleErrorAttribute>().AsExceptionFilterFor<BaseController>().PropertiesAutowired().SingleInstance();
        }
    }
}